package com.bankapp.service.bank;

import com.bankapp.domain.bank.*;
import com.bankapp.exception.bank.BankException;

import java.io.*;

public class BankService {

    public static void addClient(final Bank bank, final String name, final String surname,
                                 final Gender gender, final AbstractAccount account, final String emailAddress) {
        Client client = new Client(name, surname, gender, account, new Email(emailAddress));

        bank.addClient(client);
    }

    public static void modifyBank(final Account account, final double amount) throws BankException {
        if (amount >= 0) {
            account.deposit(amount);
        } else {
            account.withdraw(-amount);
        }

    }

    public void printBalance(final Bank bank) {
        Client[] clients = bank.getClientsArray();
        for (int i = 0; i < clients.length; i++) {
            if (clients[i] == null) {
                continue;
            } else {
                System.out.println("Client " + i + ": " + clients[i].getAccount().getBalance());
            }
        }
    }

    public void saveBank(Bank bank, String pathToBankFile) {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(pathToBankFile)))) {
            oos.writeObject(bank);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Bank readBank(String pathToBankFile) {
        Bank bankInfo = null;
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File(pathToBankFile)))) {
            bankInfo = (Bank) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return bankInfo;
    }
}
